package com.kxmall.framework.filter;

import cn.dev33.satoken.context.SaHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * ThreadLocal 清理过滤器
 * 防止线程池复用导致的用户信息串号问题
 *
 * @author kxmall
 */
@Slf4j
@Component
@WebFilter(urlPatterns = "/*")
@Order(1)
public class ThreadLocalCleanupFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("ThreadLocal清理过滤器初始化完成");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        
        String threadName = Thread.currentThread().getName();
        
        try {
            // 在请求开始前记录线程信息（调试用）
            if (log.isDebugEnabled()) {
                log.debug("请求开始 - 线程: {}", threadName);
            }
            
            chain.doFilter(request, response);
            
        } catch (Exception e) {
            log.error("请求处理异常 - 线程: {}", threadName, e);
            throw e;
        } finally {
            try {
                // 清理ThreadLocal，防止内存泄漏和数据污染
                try {
                    SaHolder.getStorage().delete("loginUser");
                } catch (Exception deleteException) {
                    // 忽略删除异常
                }

                if (log.isDebugEnabled()) {
                    log.debug("ThreadLocal清理完成 - 线程: {}", threadName);
                }
            } catch (Exception e) {
                log.error("ThreadLocal清理异常 - 线程: {}", threadName, e);
            }
        }
    }

    @Override
    public void destroy() {
        log.info("ThreadLocal清理过滤器销毁");
    }
}
